package com.willian.andrappfw.utils;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PreferenceUtil {
    private static SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ContextHolder.getContext());

    public PreferenceUtil() {
    }

    public static SharedPreferences getSharedPreferences() {
        return sp;
    }

    public static void saveObject(String key, Object obj) {
        getSharedPreferences().edit().putString(key, (new Gson()).toJson(obj)).apply();
    }

    public static <T> List<T> getObjectList(String key, Class<T> itemClass) {
        List<T> lst = new ArrayList();
        String banners = getSharedPreferences().getString(key, (String)null);
        if (TextUtils.isEmpty(banners)) {
            return lst;
        } else {
            try {
                JsonArray array = (new JsonParser()).parse(banners).getAsJsonArray();
                Iterator var5 = array.iterator();

                while(var5.hasNext()) {
                    JsonElement elem = (JsonElement)var5.next();
                    lst.add((new Gson()).fromJson(elem, itemClass));
                }
            } catch (Exception var7) {
            }

            return lst;
        }
    }

    public static <T> T getObject(String key, Class<T> objClass) {
        String banners = getSharedPreferences().getString(key, (String)null);
        return TextUtils.isEmpty(banners) ? null : (new Gson()).fromJson(banners, objClass);
    }
}

